<?php
/**
 * Descript:
 * User: lufeng501206@gmail.com
 * Date: 2017/4/10 15:45
 */

namespace App\Http\Controllers\Home;


use App\Http\Controllers\Controller;
use App\Models\Home\User;
use App\Models\LoginLogs;
use EasyWeChat\Foundation\Application;
use Illuminate\Http\Request;

class WechatController extends Controller
{
    private $options;

    public function __construct()
    {
        $this->options = [
            'debug' => false,
            'app_id' => env('WECHAT_APP_ID'),
            'secret' => env('WECHAT_SECRET'),
            'token' => env('WECHAT_TOKEN'),
            'aes_key' => env('WECHAT_AES_KEY'),
            'log' => [
                'level' => 'debug',
                'file' => '/tmp/easywechat.log',
            ],
            'oauth' => [
                'scopes' => ['snsapi_userinfo'],
                'callback' => '/callBack',
            ],
        ];
    }

    /**
     * 服务器验证
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function index()
    {
        $app = new Application($this->options);
        $response = $app->server->serve();
        return $response;
    }

    public function callBack(Request $request)
    {
        \Log::debug('回调......');
        $app = new Application($this->options);
        $oauth = $app->oauth;
        // 获取 OAuth 授权结果用户信息
        $user = $oauth->user();
        \Log::debug('用户信息=============');
        $userWechatInfo = [];
        $userWechatInfo['openid'] = $user->getId();  // 对应微信的 OPENID
        $userWechatInfo['nickname'] = $user->getNickname(); // 对应微信的 nickname
        $userWechatInfo['name'] = $user->getName(); // 对应微信的 nickname
        $userWechatInfo['avatar'] = $user->getAvatar(); // 头像网址
        \Log::debug($userWechatInfo);

        //注册登录账号
        $account = $userWechatInfo['openid'];

        $userModel = User::where('account',$account)->first();

        if (empty($userModel)) {
            $userModel = new User();
            $userModel->account = $account;
            $userWechatInfo['nickname'] = preg_replace('/[\x{10000}-\x{10FFFF}]/u', '', $userWechatInfo['nickname']);
            $userModel->name = $userWechatInfo['nickname'];
            $userModel->avatars = $userWechatInfo['avatars'];
            $userModel->mobile = '';
            $res = $userModel->save();
            if ($res) {
                \Log::debug('微信用户注册成功=============');
                $this->writeLoginLog($account,$request);
                //保存session
                $request->session()->put('login_user', $account);
            } else {
                \Log::debug('微信用户注册失败=============');
            }
        }else{
            if (empty($userModel->avatars)) {
                $userModel->avatars = $userWechatInfo['avatars'];
                $userModel->save();
            }
            $this->writeLoginLog($account,$request);
            \Log::debug('微信用户登录成功=============');
            $request->session()->put('login_user', $account);
        }
        $request->session()->put('wechat_userinfo', @json_encode($userWechatInfo));
        \Log::debug('用户信息=============');
        $RecommendUser = $request->session()->get('recommend_user');
        if (!empty($RecommendUser)) {
            $request->session()->forget('recommend_user');
            header('location:web/invite.html?recommend_user='.$RecommendUser);
        }else{
            header('location:web');
        }
    }

    /**
     * 写入登录日志
     */
    private function writeLoginLog($mobile,$request)
    {
        $loginLogModel = new LoginLogs();
        $loginLogModel->client_ip = $request->getClientIp();
        $loginLogModel->mobile = $mobile;
        $loginLogModel->save();
        return true;
    }

    public function getJSSDK(Request $request)
    {
        $url = $request->input('url');
        $app = new Application($this->options);
        $js = $app->js;
        $js = $js->setUrl($url);
        $response = $js->config([]);
        return $response;
    }
}